/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-20 10:44:26
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-21 13:51:29
 * @FilePath: \gogamewebserver\goGameWebServer\internal\common\utils\utils.go
 * @Description: 文件功能描述
 */
package utils

import (
	"bytes"
	"compress/zlib"
	"crypto/md5"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"io"

	"github.com/google/uuid"
)

// 生成uuid
func GenerateUUID() string {
	return uuid.New().String()
}

// 生成32位随机字符串
func GenerateRandomString32() string {
	return GenerateUUID()[:32]
}

func Sha256Hex(input string) string {
	// 创建SHA256哈希对象
	hasher := sha256.New()

	// 写入输入数据
	hasher.Write([]byte(input))

	// 计算哈希值并转换为十六进制字符串
	hashBytes := hasher.Sum(nil)
	hashString := hex.EncodeToString(hashBytes)

	return hashString
}

// MD5加密
func MD5Hex(input string) string {
	// 创建MD5哈希对象
	hasher := md5.New()

	// 写入输入数据
	hasher.Write([]byte(input))

	// 计算哈希值并转换为十六进制字符串
	hashBytes := hasher.Sum(nil)
	hashString := hex.EncodeToString(hashBytes)

	return hashString
}

// ZlibEncode
func ZlibEncode(str string) (string, error) {
	var buf bytes.Buffer
	zw := zlib.NewWriter(&buf)
	if _, err := zw.Write([]byte(str)); err != nil {
		_ = zw.Close()
		return "", err
	}
	if err := zw.Close(); err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(buf.Bytes()), nil
}

// ZlibDecode
func ZlibDecode(str string) (string, error) {
	data, err := base64.StdEncoding.DecodeString(str)
	if err != nil {
		return "", err
	}
	zr, err := zlib.NewReader(bytes.NewReader(data))
	if err != nil {
		return "", err
	}
	defer zr.Close()

	out, err := io.ReadAll(zr)
	if err != nil {
		return "", err
	}
	return string(out), nil
}
